package com.zjun.demo.experimentaldemo.album_operate

import android.Manifest.permission.READ_EXTERNAL_STORAGE
import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.core.graphics.drawable.toBitmap
import java.io.File
import java.io.InputStream
import android.database.Cursor
import android.os.Environment.getExternalStoragePublicDirectory
import androidx.core.content.PermissionChecker
import androidx.core.content.PermissionChecker.PERMISSION_GRANTED
import com.zjun.demo.experimentaldemo.R


class AlbumOperateActivity : AppCompatActivity() {

    private var msdf = arrayOf(R.drawable.ic_launcher_foreground, R.drawable.ktv)


    private lateinit var lastFileName:String

    private lateinit var image: ImageView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_album_operate)
        image = findViewById(R.id.imageView)
    }

    fun saveImage(view: View) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            if (PermissionChecker.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) == PERMISSION_GRANTED) {
                insertPicture()
            } else {
                requestPermissions(arrayOf(WRITE_EXTERNAL_STORAGE), 5)
            }
        } else {
            insertPicture()
        }
    }

    fun deleteImage(view: View) {
        clearAppPictures()
    }

    fun queryAppImage(view: View) {
        if(!this::lastFileName.isInitialized){
            showToast("没有保存图片")
            return
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
            if (PermissionChecker.checkSelfPermission(this, READ_EXTERNAL_STORAGE) == PERMISSION_GRANTED) {
                queryImage()
            } else {
                requestPermissions(arrayOf(READ_EXTERNAL_STORAGE), 6)
            }
        } else {
            queryImage()
        }
    }

    private fun queryImage(){
        val isExist = contentResolver.queryMedia(
            lastFileName,
            "wen"
        )
        showToast("图片是否存在 $isExist")
    }


    fun deleteSpecifyImage(view: View) {
        contentResolver.deleteSpecifyImage(
            lastFileName,
            Environment.DIRECTORY_PICTURES + File.separator + "Fundark" + File.separator
        )
    }

    var s =0

    // 保存到外部储存-公有目录-Picture内，并且无需储存权限
    private fun insertPicture() {
        image.setImageResource(msdf[s])
        if(s==1){
            s=0
        }else{
            s++
        }
        image.drawable?.let {
            val bitmap = it.toBitmap()
            val fileName = "${System.currentTimeMillis()}.jpg"
            val uri = bitmap.saveToAlbum(this,fileName,"wen")
            lastFileName = fileName
            if(uri!=null){
                showToast("导出到相册成功")
            }
        }
    }

    private fun showToast(s: String) {
        Toast.makeText(this, s, Toast.LENGTH_SHORT).show()
    }

    // 使用MediaStore方式将流写入相册
    @Suppress("SameParameterValue")
    private fun insert2Album(inputStream: InputStream, type: String,relativePath:String = "Fundark") {
        val fileName = "${type}_${System.currentTimeMillis()}.jpg"
        lastFileName = fileName
        val contentValues = ContentValues()
        contentValues.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, fileName)
        // Android 10，路径保存在RELATIVE_PATH
        val collection: Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            //RELATIVE_PATH 字段表示相对路径，Fundark为相册下专有目录
            val path = Environment.DIRECTORY_PICTURES + File.separator + relativePath + File.separator
            contentValues.put(MediaStore.Images.ImageColumns.RELATIVE_PATH, path)
            collection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
        } else {
            val pictures = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            val saveDir = File(pictures, relativePath)
            if (!saveDir.exists()) {
                saveDir.mkdirs()
            }
            val imageFile = File(saveDir, fileName)
            //DATA字段在Android 10.0 之后已经废弃（Android 11又启用了，但是只读）
            contentValues.put(MediaStore.Images.ImageColumns.DATA, imageFile.absolutePath)
            collection = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        }
        // 插入相册
        val uri = contentResolver.insert(collection, contentValues)
        // 写入文件
        uri?.let {
            write2File(it, inputStream)
            val pictures = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            val saveDir = File(pictures, relativePath)
            if (!saveDir.exists()) {
                saveDir.mkdirs()
            }
            val imageFile = File(saveDir, fileName)
        }
    }

    private fun write2File(uri: Uri, inputStream: InputStream) {
        // 从Uri构造输出流
        contentResolver.openOutputStream(uri)?.use { outputStream ->
            val byteArray = ByteArray(1024)
            var len: Int
            do {
                //从输入流里读取数据
                len = inputStream.read(byteArray)
                if (len != -1) {
                    outputStream.write(byteArray, 0, len)
                    outputStream.flush()
                }
            } while (len != -1)
        }
    }

    private fun clearCachePictures(context: Context) {
        // 外部储存-私有目录-files-Pictures目录
        context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.let { dir ->
            // 删除其中的图片
            try {
                val pics = dir.listFiles()
                pics?.forEach { pic ->
                    pic.delete()
                }
                showToast("清除缓存成功")
            } catch (e: Exception) {
                e.printStackTrace()
                showToast("清除缓存失败")
            }
        }
    }

    private fun clearAppPictures() {
        val selection: String
        val selectionArgs: String
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            selection = "${MediaStore.Images.ImageColumns.RELATIVE_PATH} like ?"
            selectionArgs = "%" + Environment.DIRECTORY_PICTURES + File.separator + "Fundark" + "%"
        } else {
            val dstPath = StringBuilder().let { sb ->
                sb.append(getExternalFilesDir(Environment.DIRECTORY_PICTURES)!!.path)
                sb.append(File.separator)
                sb.append("Fundark")
                sb.toString()
            }
            selection = "${MediaStore.Images.ImageColumns.DATA} like ?"
            selectionArgs = "%$dstPath%"
        }
        val num = contentResolver.delete(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            selection,
            arrayOf(selectionArgs)
        )
        showToast("删除本应用相册图片${num}张")
    }

    fun print() {
        val projection = arrayOf(MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DISPLAY_NAME) // 只获取图片id列
        val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI // 外部存储器上的图像内容URI
        val cursor = contentResolver.query(uri, projection, null, null, null)

        if (cursor != null && cursor.moveToFirst()) {
            do {
                val idColumnIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns._ID)
                val s = cursor.columnNames

                val displayNameIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME)
                val imageId = cursor.getLong(idColumnIndex) // 获取图片id
                val displayName = cursor.getString(displayNameIndex) // 获取图片id
                val imageUri = ContentUris.withAppendedId(uri, imageId.toLong()) // 构建完整的图片URI

                // 这里可以根据需求对每张图片进行处理或者显示
                Log.d("TAG", "Image URI: $imageUri")
            } while (cursor.moveToNext())
        } else {
            Log.e("TAG", "No images found.")
        }
        cursor!!.close()
    }

    fun isImagePathExists(name: String, relativePath: String): Boolean {
        val contentResolver = contentResolver
        // 构建查询条件
        val projection = arrayOf(MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.ImageColumns.RELATIVE_PATH)
        val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val selection = "${MediaStore.Images.Media.DISPLAY_NAME}=? AND ${MediaStore.Images.Media.RELATIVE_PATH}=? "
//        val selection = "${MediaStore.Images.Media.DISPLAY_NAME}=?"
        val selectionArgs = arrayOf(name, relativePath)
        var cursor: Cursor? = null
        return try {
            // 执行查询操作
            cursor = contentResolver.query(uri, projection, selection, selectionArgs, null)
            if (cursor == null) {
                false
            } else {
                if (cursor.moveToFirst()) {
                    do {
                        val displayNameIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME)
//                        val displayNameIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.RELATIVE_PATH)
                        val displayName = cursor.getString(displayNameIndex)
                        if (displayName == name) {
                            return true
                        }
                    } while (cursor.moveToNext())
                    false
                } else {
                    false
                }
            }
        } finally {
            cursor?.close()
        }
    }

}